﻿
using System.Collections.Generic;
using System.Data;
using System;
using System.Web;
using System.Text;
using System.Security.Cryptography;
using System.IO;
using ZHDJ.MobileInterface.Utils;
namespace ZHDJ.MobileInterface
{
    public partial class GetCloudStudyUrl : AbstractBasePage
    {
        protected override OutParam BusinessProcess<InParam, OutParam>(InParam inParam)
        {
            // 业务逻辑返回的响应对象  
            GetCloudStudyOutParam result = new GetCloudStudyOutParam();
            GetCloudStudyInParam param = new GetCloudStudyInParam();
            string logMsg = "";
            bool isFlag = true;

            try
            {
                param = inParam as GetCloudStudyInParam;
                if (param == null || string.IsNullOrEmpty(param.user_id))
                {
                    result.code = "0";
                    result.desc = "用户ID不能为空";
                    isFlag = false;
                }

                if (isFlag)
                {
                    if (CommonUtils.IsDisableUsers(param.user_id))
                    {
                        result.code = "0";
                        result.desc = "用户状态有问题，请联系管理员";

                        isFlag = false;
                    }
                }

                if (isFlag)
                {
                    string url = System.Configuration.ConfigurationManager.AppSettings["SXT.Cloud.Url"];
                    if (string.IsNullOrEmpty(url))
                    {
                        result.code = "0";
                        result.desc = "该栏目正在建设中，敬请期待！";
                    }
                    else
                    {
                        result.data.wap_url = this.GetUrl(param.user_id);
                    }
                }
                logMsg = result.desc;
            }
            catch (Exception ex)
            {
                result.code = "0";
                result.desc = "操作异常，多次出现请联系管理员";
                logMsg = ex.Message + ":" + ex.StackTrace;
            }

            CommonUtils.InsertMobileInterfaceLog(SystemCode +"-GetGetCloudStudyList", SerializeHelper.JsonSerializer<GetCloudStudyInParam>(param), logMsg);
            return result as OutParam;
        }

        protected void Page_Load(object sender, System.EventArgs e)
        {
            if (string.Compare(Request.QueryString["Safe"], "False", true) == 0)
                ProcessRequest<GetCloudStudyInParam, GetCloudStudyOutParam>();
            else
                SafeProcessRequest<GetCloudStudyInParam, GetCloudStudyOutParam>();
        }



        /// <summary>
        /// 获取返回的url
        /// </summary>
        /// <param name="loginID"></param>
        /// <returns></returns>
        public string GetUrl(string loginID)
        {
            string key = System.Configuration.ConfigurationManager.AppSettings["SXT.Cloud.Url.Key"];
            string iv = System.Configuration.ConfigurationManager.AppSettings["SXT.Cloud.Url.IV"];
            string url = System.Configuration.ConfigurationManager.AppSettings["SXT.Cloud.Url"];
            string backUrl = System.Configuration.ConfigurationManager.AppSettings["SXT.Cloud.Url.BackUrl"]; ;
            DataSet ds = InterfaceHelper.GetMembersByFilter(" loginid ='" + loginID + "'");
            if (ds == null || ds.Tables.Count < 1 || ds.Tables[0].Rows.Count < 1)
            {
                return url;
            }
            if (string.IsNullOrEmpty(key))
            {
                key = "Do1_Info_thParty".PadRight(24, 'a');
            }
            else
            {
                key = key.PadRight(24, 'a');
            }
            string phone = ds.Tables[0].Rows[0]["MobileNo"].ToString();
            string pwd = ds.Tables[0].Rows[0]["Password"].ToString();
            //string jiamiStr=EncryptWithJava(string.Format(this.SN, loginID, pwd), key);
            string userName = ds.Tables[0].Rows[0]["UserName"].ToString();
            string email = ds.Tables[0].Rows[0]["Email"].ToString();
            string jiamiStr = JavaDES.Encode("{"+string.Format(this.SN, loginID, pwd, DateTime.Now.ToString("yyyy-MM-dd"), userName, phone, email)+"}", key, iv);
            string backUrltemp = HttpUtility.UrlEncode(string.Format(backUrl, jiamiStr));
            return url + "&backurl=" + backUrltemp;
        }

        /// <summary>
        /// 加密串
        /// </summary>
        private string SN
        {
            get
            {
                //<uid>TH0011117</uid><pswd>111222</pswd><gid>7395</gid><date>2015-01-22</date>
                string jiamistring = System.Configuration.ConfigurationManager.AppSettings["SXT.Cloud.JiamiString"];
                return jiamistring;
            }
        }

       

        public static string EncryptWithJava( string str,string key)
        {
            if (key.Length < 8 || string.IsNullOrEmpty(str))
            {
                throw new Exception("加密key小于8或者加密字符串为空！");
            }
            byte[] bKey = Encoding.UTF8.GetBytes(key.Substring(0, 8));
            byte[] bIV = { 0x01};
            byte[] bStr = Encoding.UTF8.GetBytes(str);
            try
            {
                DESCryptoServiceProvider desc = new DESCryptoServiceProvider();
                desc.Padding = PaddingMode.PKCS7;//补位  
                desc.Mode = CipherMode.ECB;//此模式，对加密，IV无意义  
                using (MemoryStream mStream = new MemoryStream())
                {
                    using (CryptoStream cStream = new CryptoStream(mStream, desc.CreateEncryptor(bKey, bIV), CryptoStreamMode.Write))
                    {
                        cStream.Write(bStr, 0, bStr.Length);
                        cStream.FlushFinalBlock();
                        StringBuilder ret = new StringBuilder();
                        byte[] res = mStream.ToArray();
                        foreach (byte b in res)
                        {
                            ret.AppendFormat("{0:x2}", b);
                        }
                        return ret.ToString().ToUpper();
                    }
                }
            }
            catch
            {
                return string.Empty;
            }
        } 
       
    }



    #region 请求参数
    public class GetCloudStudyInParam
    {
        /// <summary>
        /// 	用户ID
        /// </summary>
        public string user_id
        { get; set; }
    }
    #endregion

    #region 结果参数
    public class GetCloudStudyOutParam
    {
        public GetCloudStudyOutParam()
        {
            code = "1";
            desc = "操作成功";
            data = new GetCloudStudy();
        }

        /// <summary>
        /// 返回结果 具体见接口返回对照码 1	成功 0	失败 2	请求非法 加密结果和传入的MD5字符串进行比较，如果相同则执行接口操作，否则返回1001错误响应码
        /// </summary>
        public string code
        { get; set; }

        /// <summary>
        /// 结果描述 成功和失败都需要
        /// </summary>
        public string desc
        { get; set; }

        /// <summary>
        /// 
        /// </summary>
        public GetCloudStudy data
        { get; set; }
    }

    /// <summary>
    /// 资讯详情
    /// </summary>
    public class GetCloudStudy
    {
        /// <summary>
        ///		链接地址
        /// </summary>
        public string wap_url
        { get; set; }
    }
    #endregion
}